package com.cloud.weichat;

/**
 * weixin
 *
 * @author
 * @create 2017-09-22 16:41
 **/

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import net.sf.json.JSONObject;

/**
 * 类说明
 */
public class WeiChatUtil {

    /**
     *
     * @param userId 接收用户的id
     * @param title 企业微信的标题
     * @param summary 概要说明
     * @param url 用户在企业微信中点击的链接地址
     * @param picUrl 企业微信的摘要图片
     * @return
     */
    public static boolean sendWeiChat(String userId,String title,String summary,String url,String picUrl) {

        //企业号id
        String corpid = PARAMUTIL.getString("corpid");
        //企业号密钥
        String serect = PARAMUTIL.getString("serect");
        //agentId
        String agentid = PARAMUTIL.getString("agentid");
        //token获取地址
        String accesstokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SERCRET";
        accesstokenurl = accesstokenurl.replace("ID", corpid).replace("SERCRET", serect);


        //获取token
        JSONObject accesstoken = HttpRequest(accesstokenurl, "GET", null);

        String token = accesstoken.getString("access_token");
        System.out.println("*******corpid="+corpid);
        System.out.println("*******serect="+serect);
        System.out.println("*******agentid="+agentid);

        //消息发送接口地址
        String posturl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
        posturl = posturl.replace("ACCESS_TOKEN", token);
        //消息内容
        String postdata = STextMsg("ZhangLi", "", "", agentid, "zhanglid 的测试，于小青进行测试");
        // 图文消息发送
//        String postPicAndMsg = STextMsgPic("ZhangLi","","","1000002",title,
//                "今年中秋节公司有豪礼相送","https://www.jd.com?userid=ZhangLi",
//                "https://img14.360buyimg.com/babel/jfs/t8260/268/2102570083/132247/7944a840/59c4cdf2N9ea2b50f.jpg",
//                "更多");

        String postPicAndMsg = STextMsgPic(userId,"","",agentid,title,
                summary,url+"&userId="+userId,
                picUrl,
                "更多");
        //发送消息
//        JSONObject result = HttpRequestUtils.httpPost(posturl, postdata, false);
        //发送图文消息
        JSONObject resultPic = HttpRequestUtils.httpPost(posturl, postPicAndMsg, false);

//        JSONObject result = HttpRequest(posturl, "GET", postdata);
        //结果输出
        System.out.println(resultPic);
        return true;
    }

    /**
     * text消息
     *
     * @param touser  UserID列表（消息接收者，多个接收者用‘|’分隔）。特殊情况：指定为@all，则向关注该企业应用的全部成员发送————"touser": "UserID1|UserID2|UserID3"
     * @param toparty PartyID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数————"toparty": " PartyID1 | PartyID2 "
     * @param totag   TagID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数————"totag": " TagID1 | TagID2 "
     * @param agentid 企业应用的id，整型。可在应用的设置页面查看
     * @param content 消息内容
     */
    public static String STextMsg(String touser, String toparty, String totag, String agentid, String content) {
        String PostData = "{\"touser\": \"%s\",\"toparty\": \"%s\",\"totag\": \"%s\",\"msgtype\": \"text\",\"agentid\":\"%s\",\"text\": {\"content\": \"%s\"},\"safe\":\"0\"}";
        System.out.println(PostData);
        return String.format(PostData, touser, toparty, totag, agentid, content);
    }

    /**
     * 图文消息的发送
     * @param touser
     * @param toparty
     * @param totag
     * @param agentid
     * @param title
     * @param desc
     * @param url
     * @param picurl
     * @param btntxt
     * @return
     */
    public static String STextMsgPic(String touser, String toparty, String totag, String agentid, String title, String desc, String url, String picurl, String btntxt) {
        String PostData = "{\"touser\": \"%s\",\"toparty\": \"%s\",\"totag\": \"%s\",\"msgtype\": \"news\",\"agentid\":\"%s\"," +
                "\"news\" : {"+
                "       \"articles\" : [\n" +
                "           {\n" +
                "               \"title\" : \"%s\"," +
                "               \"description\" : \"%s\"," +
                "               \"url\" : \"%s\"," +
                "               \"picurl\" : \"%s\"," +
                "               \"btntxt\":\"%s\"" +
                "           }\n" +
                "        ]"+
                "}";
        System.out.println(PostData);
        return String.format(PostData, touser, toparty, totag, agentid, title,desc,url,picurl,btntxt);
    }

    public static JSONObject HttpRequest(String requestUrl, String requestMethod,
                                         String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        OutputStream out = null;
        InputStream input = null;
        InputStreamReader inputReader = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            // 建立连接
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置http头部信息
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            // 写入消息实体
            if (outputStr != null) {
                out = connection.getOutputStream();
                out.write(outputStr.getBytes("UTF-8"));
            }
            // 流处理
            input = connection.getInputStream();
            inputReader = new InputStreamReader(input, "UTF-8");
            reader = new BufferedReader(inputReader);
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String re = buffer.toString();
            jsonObject = JSONObject.fromObject(re);
        } catch (Exception e) {
            //日志处理等，请自行实现
            e.printStackTrace();
        } finally {
            try {
                if (outputStr != null) {
                    out.close();
                }
                // 关闭连接、释放资源
                if (reader != null) {
                    reader.close();
                }
                if (inputReader != null) {
                    inputReader.close();
                }
                if (input != null) {
                    input.close();
                }
                input = null;
                connection.disconnect();
            } catch (Exception e) {
                //日志处理等，请自行实现
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static void main(String[] args) {
        String test ="zhangli#1,yuxq#2,sanyi#3,wuliu#4";
        String []sp =  test.split(",");
        for (int i = 0; i < sp.length; i++) {
            System.out.println(sp[i]);
            String  smm[] = sp[i].split("#");
            for (int i1 = 0; i1 < smm.length; i1++) {
                System.out.println(smm[i1]);

            }
            System.out.println("end");

        }

    }

}
